# Copyright (c) 2009 Supreet Sethi. All rights reserved.
# Licensed Artistic License

import urllib2
import urllib
import sys
import struct
from socket import gethostbyaddr, gethostname, inet_aton
#from md5 import md5 python older version
from hashlib import md5
from blowfish import Blowfish
from binascii import hexlify
import subprocess as sp
import re

class PlatformFunctionNotFound(Exception):
    pass



class Platform(object):
    sysIP = gethostbyaddr(gethostname())[2]
    def __init__(self):
        pass
    

    
    def getTimeStamp(self, serverTime):
        (sDate,sTime)=serverTime.split()
        dateVec=sDate.split("-")
        dateStr=''.join([phi for phi in dateVec])
        timeVec=sTime.split(":")
        timeStr=''.join([phi for phi in timeVec])
        delta=int(dateStr)-int(timeStr)
        tstamp=''.join([`int(phi)+0x30` for phi in `delta`])
        return tstamp

    def getSystemIP(self):
        return self.sysIP

    def getNetAddress(self, iDotAddr):
        return str(struct.unpack('!L', inet_aton(iDotAddr))[0])
    
    def getMD5(self, String):
        return md5(String).hexdigest()

    def getMACAddress(self):
        osname = sys.platform
        if hasattr(self, 'getMacAddress%s' % osname):
            return getattr(self, 'getMacAddress%s' % osname)()
        else:
            raise PlatformFunctionNotFound()
    

    def getProcStdOut(self, cmd):
        conPipe = sp.Popen(cmd, stdout=sp.PIPE,shell=True)
        conOut = conPipe.communicate()[0]
        return conOut



    def getMacAddresslinux2(self):
        conOut=self.getProcStdOut("/sbin/ifconfig")
        conOut='@'.join([phi for phi in conOut.splitlines()])
        m = re.search('.*HWaddr (.*?)@.*inet addr:%s.*'% self.sysIP,conOut)
        gMacAddr=m.group(1).strip().lower()
        return gMacAddr

    def getEncrypted(self, key, text):
        bf = Blowfish(key)
        content = bf.easy_encrypt(text)
        return hexlify(content)
    





def postToServer(url, data, constants):
    headers = {'User-Agent': 'BBClient'}
    if data:
        if type(data) == type(''):
            data = urllib.urlencode({'cons':data})
        if type(data) == type({}):
            data = urllib.urlencode(data)
    print url, data
    req = urllib2.Request(url, data, headers)
    try:
        response = urllib2.urlopen(req)
    except Exception, e:
        print e
        sys.exit(5)
        
    content = response.read()
    if constants.verbose == True:
        print content
        print len(content)
    return content

 
